//
//  DDLoginViewController.m
//  DingDongZP
//
//  Created by Jyh on 16/3/13.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

#import "DDLoginViewController.h"
#import "DDLoginService.h"
#import "DDLoginUserManager.h"
#import "DDRegisterViewController.h"
#import "DDquickViewController.h"
#import "DDforgetViewController.h"
#import "DDCommunicatedStore.h"
#import "DDUserInfoService.h"
#import "DDUtils.h"


@interface DDLoginViewController () <UITextFieldDelegate>

@property (weak, nonatomic, readwrite) IBOutlet UIImageView    *headImgView;
@property (weak, nonatomic) IBOutlet UIView         *accountView;
@property (weak, nonatomic) IBOutlet UIView         *passwordView;

@property (weak, nonatomic) IBOutlet UIButton       *passwordButton;
@property (weak, nonatomic) IBOutlet UITextField    *accountTF;
@property (weak, nonatomic) IBOutlet UITextField    *passwordTF;
@property (weak, nonatomic) IBOutlet UIButton       *loginBtn;
@property (strong, nonatomic) DDLoginService        *loginService;

@property (nonatomic, strong) DDUserInfoService *userService;
@property (nonatomic, strong) DDBossInfoService *bossService;


- (IBAction)onRegisterButtonClick:(id)sender;

@end

@implementation DDLoginViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        
    }
    return self;
}

- (void)awakeFromNib
{
    
}

- (DDUserInfoService *)userService
{
    if (!_userService){
        _userService = [[DDUserInfoService alloc] init];
    }
    return _userService;
}

- (DDBossInfoService *)bossService
{
    if (!_bossService){
        _bossService = [[DDBossInfoService alloc] init];
    }
    return _bossService;
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

- (void) viewDidLoad {
    [super viewDidLoad];
    
    UIButton *backbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    backbutton.frame = CGRectMake(15, 35, 35, 35);
    backbutton.layer.masksToBounds = YES;
    backbutton.layer.cornerRadius = 35/2;
    [backbutton setBackgroundImage:[UIImage imageNamed:@"返回back"] forState:UIControlStateNormal];
    [backbutton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backbutton];
    
    
    //    [self.rdv_tabBarController setTabBarHidden:true animated:true];
    self.navigationController.view.backgroundColor = COLOR_BACKGROUND_GRAY;
    self.view.backgroundColor = COLOR_BACKGROUND_GRAY;
    
    if(!self.loginService) {
        self.loginService = [[DDLoginService alloc] init];
    }
    
    [self setDefaultContent];
    [self setSubview];
    [self setupSignal];
}

- (void)backAction
{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void) viewDidAppear:(BOOL)animated {
    
    [self.rdv_tabBarController setTabBarHidden:true animated:true];
    if ([DDLoginUserManager account]) {
        
        self.accountTF.text = [DDLoginUserManager account];
        
    } else {
        
    }
}

- (void) setupSignal {
    
    WEAKSELF
    
    RACSignal *phoneSignal = [self.accountTF.rac_textSignal map:^id(NSString *text) {
        
        if (text.length >= 11) {
            
            NSString *phoneNum = [text substringToIndex:11];
            weakSelf.accountTF.text = phoneNum;
        } else {
            
            weakSelf.accountTF.text = text;
        }
        
        return @(text.length == 11 ? true:false);
    }];
    
    RACSignal *passwordSignal = [self.passwordTF.rac_textSignal map:^id(NSString *text) {
        
        return @(text.length >= 6 ? true:false);
    }];
    
    
    RACSignal *loginSignal = [RACSignal combineLatest:@[phoneSignal,passwordSignal] reduce:^id (NSNumber *phoneNumValid, NSNumber *passwordValid){
        
        
        if (weakSelf.accountTF.text.length == 11) {
            
            return @([passwordValid boolValue]);
        } else {
            
            return @([phoneNumValid boolValue] && [passwordValid boolValue]);
        }
        
    }];
    
    
    [loginSignal subscribeNext:^(NSNumber *loginEnable) {
        
        if ([loginEnable boolValue]) {
            
            weakSelf.loginBtn.enabled = true;
            [weakSelf.loginBtn setBackgroundColor:COLOR_NAVIGATIONBAR];
            
            
        } else {
            
            weakSelf.loginBtn.enabled = false;
            [weakSelf.loginBtn setBackgroundColor:COLOR_BORDER_GRAY];
            
        }
        
    }];
    
    
    [[self rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(id x) {
        
        [weakSelf.accountTF endEditing:true];
        [weakSelf.passwordTF endEditing:true];
    }];
}

- (void)setDefaultContent {
    
    self.navigationController.navigationBar.translucent = false;
    
    //    CGFloat headImgH = IPHONE6UP ? 160:140;
    //    [self.view layoutIfNeeded];
    //    
    //    [self.headImgView setHeight:headImgH];
}

- (void)setSubview
{
    self.accountView.layer.masksToBounds = YES;
    self.accountView.layer.cornerRadius = 5.f;
    
    self.passwordView.layer.masksToBounds = YES;
    self.passwordView.layer.cornerRadius = 5.f;
    
    [self.passwordButton setImage:[UIImage imageNamed:@"word_close"] forState:UIControlStateNormal];
    [self.passwordButton setImage:[UIImage imageNamed:@"word_open"] forState:UIControlStateSelected];
    
    self.passwordTF.secureTextEntry = YES;
    self.accountTF.keyboardType = UIKeyboardTypePhonePad;
    
    self.view.userInteractionEnabled = true;
    
    WEAKSELF
    [self.view bk_whenTapped:^{
        [weakSelf.accountTF resignFirstResponder];
        [weakSelf.passwordTF resignFirstResponder];
    }];
}

#pragma mark --- IBAction Method

- (IBAction)passwordButtonSeleted:(UIButton *)sender {
    sender.selected = !sender.selected;
    
    // 解决密码框secureTextEntry属性切换时候，光标不准的bug。
    NSString *tempString = self.passwordTF.text;
    self.passwordTF.text = @"";
    self.passwordTF.secureTextEntry = !sender.selected;
    self.passwordTF.text = tempString;
}

- (IBAction)onLoginButton:(id)sender {
    
    [self.view endEditing:YES];
    
    [self showLoading];
    
    WEAKSELF
    if (self.loginService) {
                
        NSString *base64 = [DDUtils ddLoginEncode:self.accountTF.text key:self.passwordTF.text];
        [self.loginService queryLoginWithMobile:self.accountTF.text passWord:base64 successBlock:^(id responseObject) {
            
            //            NSLog(@"---resp%@",responseObject);
            
            [weakSelf hideLoading];
            if ([weakSelf isValidateResponseData:responseObject]) {
                
                //  如果不是原来的帐号，清除一些与帐号相关的缓存数据
                if (![weakSelf.accountTF.text isEqualToString:[DDLoginUserManager account]]) {
                    
                    [[DDCommunicatedStore sharedStore] clearStore];
                }
                
                // 登录成功
                [DDLoginUserManager setAccount:weakSelf.accountTF.text];
                // 假如未设置，默认牛人端
                if ([DDClientInfoManager clientType] == DDClientTypeNone) {
                    
                    [DDClientInfoManager initClientType:DDClientTypeCattle];
                }
                
                // 保存token密码
                [DDLoginUserManager setToken:responseObject[@"data"]];
                
                
                if ([DDClientInfoManager clientType] == DDClientTypeCattle) {
                    
                    // 保存牛人段userid
                    [self.userService queryUserInfo:^(DDUserInfoModel *model) {
                        [DDLoginUserManager setWeixin:model.weixin];
                        [DDLoginUserManager setUserID:model.userid];
                    }];
                    
                }
                
                if ([DDClientInfoManager clientType] == DDClientTypeBoss) {
                    
                    // 保存Boss 端userid
                    [self.bossService queryBossInfoWithSuccessBlock:^(id responseObject) {
                        DDBossInfo *model = [DDBossInfo yy_modelWithJSON:responseObject[@"data"]];
                        [DDLoginUserManager setWeixin:model.weixin];
                        [DDLoginUserManager setUserID:model.userid];
                    } failBlock:nil];
                    
                }
                
                [weakSelf exitWithSuccess];
                
                
            } else if([[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"code"]]isEqualToString:@"0"]) {
                
                //                [weakSelf showText:[responseObject objectForKey:@"msg"]];
                [[LDShowHUB shareInstance] showToastNoti:[responseObject objectForKey:@"msg"]];
            }
            
        } failBlock:^(id responseObject, NSError *error) {
            
            [weakSelf hideLoading];
            [weakSelf requestFaild];
        }];
    }
}

//忘记密码
- (IBAction)forgotSecretBtn:(id)sender {
    
    LDForgotPsVC *vc = [[LDForgotPsVC alloc]init];
    [self.navigationController pushViewController:vc animated:false];
    
}
//快捷登录
- (IBAction)quickLoginButton:(id)sender {
    
    LDExpressLoginVC *vc = [[LDExpressLoginVC alloc]init];
    [self.navigationController pushViewController:vc animated:false];
}


#pragma mark --- Login Method

- (void)exitWithSuccess
{
    if (self.loginSuccessBlock) {
        self.loginSuccessBlock();
    }
}


#pragma mark
#pragma mark - UITextFieldDelegate

//- (void)textFieldDidBeginEditing:(UITextField *)textField
//{
//    if (self.view.bounds.origin.y > 200) {
//        return;
//    }
//    CGRect newbounds = self.view.bounds;
//    newbounds.origin.y +=200;
//    
//    self.navigationItem.title = @"登录";
//    [UIView animateWithDuration:.3f animations:^{
//        self.view.bounds = newbounds;
//    }];
//}
//
//- (void)textFieldDidEndEditing:(UITextField *)textField
//{
//    self.navigationItem.title = @"";
//    if (self.view.bounds.origin.y == 200) {
//        CGRect newbounds = self.view.bounds;
//        newbounds.origin.y = 0;
//        
//        [UIView animateWithDuration:.3f animations:^{
//            self.view.bounds = newbounds;
//        }];
//    }
//}

- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

@end
